#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include "../../src/locks/spinlock.h"
#include "../../src/locks/backoff_spinlock.h"

#define NUM_THREADS 4
#define ITERATIONS 1000000
#define TEST_ROUNDS 5

typedef struct {
    const char* name;
    void (*init)(void*);
    void (*lock)(void*);
    void (*unlock)(void*);
    void* lock_instance;
} lock_variant_t;

// 测试函数
double run_test(lock_variant_t* lock) {
    pthread_t threads[NUM_THREADS];
    struct timespec start, end;
    long shared_counter = 0;
    
    lock->init(lock->lock_instance);
    clock_gettime(CLOCK_MONOTONIC, &start);
    
    // 创建线程并等待完成...
    
    clock_gettime(CLOCK_MONOTONIC, &end);
    double time_spent = (end.tv_sec - start.tv_sec) +
                       (end.tv_nsec - start.tv_nsec) / 1e9;
    return time_spent;
}

int main() {
    spinlock_t basic_lock;
    backoff_spinlock_t backoff_lock;
    
    lock_variant_t variants[] = {
        {
            .name = "Basic Spinlock",
            .init = (void(*)(void*))spinlock_init,
            .lock = (void(*)(void*))spinlock_lock,
            .unlock = (void(*)(void*))spinlock_unlock,
            .lock_instance = &basic_lock
        },
        {
            .name = "Backoff Spinlock",
            .init = (void(*)(void*))backoff_spinlock_init,
            .lock = (void(*)(void*))backoff_spinlock_lock,
            .unlock = (void(*)(void*))backoff_spinlock_unlock,
            .lock_instance = &backoff_lock
        }
    };
    
    // 运行多轮测试并计算平均值
    for (size_t i = 0; i < sizeof(variants)/sizeof(variants[0]); i++) {
        double total_time = 0;
        for (int round = 0; round < TEST_ROUNDS; round++) {
            total_time += run_test(&variants[i]);
        }
        printf("%s average time: %.4f seconds\n", 
               variants[i].name, total_time / TEST_ROUNDS);
    }
    
    return 0;
} 